import { stringify } from 'query-string';

const APIKey = 'G8wTsHW4e7lPyCDKXhgtBQfLsmVjMNEr';
let timer:NodeJS.Timeout|null = null;
export function req() {
    const url = 'http://openapi.baidu.com/oauth/2.0/authorize';
    // const xhr = new XMLHttpRequest();
    // xhr.send();
    // axios.get(url, {
    //     params: {
    //         'client_id': APIKey,
    //         'response_type': 'code',
    //         'redirect_uri': 'oob',
    //         display: 'popup',
    //     },
    // }).then((res)=>{
    //
    // });
    // const uri = encodeURIComponent('http://openapi.baidu.com/oauth/2.0/login_success');
    // const uri = encodeURIComponent('http://127.0.0.1:8080');
    const ret = stringify({
        'client_id': APIKey,
        'response_type': 'token',
        'redirect_uri': 'oob',
        'display': 'dialog',
        'qrcode': 1,
        'force_login': 1,
        'scope': 'basic,netdisk',
        'grant_type': 'implicit_grant',
    });
    console.log(ret);
    const fullUrl = `${url}?${ret}`;
    const height = 560;
    const width = 660;
    const top = (window.screen.availHeight - 30 - height) / 2;
    const left = (window.screen.availWidth - 10 - width) / 2;
    const features = {
        height: height,
        innerHeight: height,
        width: width,
        innerWidth: width,
        left,
        top,
        status: 'no',
        toolbar: 'no',
        menubar: 'no',
        location: 'no',
        resizable: 'no',
        scrollbars: 'no',
        titlebar: 'no',
    };
    const str = genFeatures(features);
    window.open(fullUrl, 'baidu_auto', str);
    clearTimer();
    timer = setInterval(()=>{
        const uInfo = localStorage.getItem('baiduUinfo');
        console.log('check auto: ', uInfo);
    }, 300);
    
}
function clearTimer() {
    if (timer !== null) {
        clearInterval(timer);
        timer = null;
    }
}
function genFeatures(params: any): string {
    const ret: string[] = [];
    Object.keys(params).forEach(key => {
        ret.push(`${key}=${params[key]}`);
    });
    return ret.join(',');
}

// https://openapi.baidu.com/oauth/2.0/authorize?
// response_type=token
// client_id=zQfDGri8cD2zz7seeYWbbjeek3gSpr0n&
// redirect_uri=https%3A%2F%2Fwww.iodraw.com%2Fauth&
// scope=basic,netdisk&
// display=tv&
// qrcode=1&
// force_login=1